<template>
  <CommonPage title="社区定义" content-row>
    <div
      class="w-72 pr-2"
      :class="[!loadingRegion && regionData.length === 0 ? 'flex flex-col items-center justify-center' : '']"
    >
      <a-skeleton v-if="loadingRegion" loading active></a-skeleton>
      <a-tree
        v-else-if="regionData.length > 0"
        v-model:selected-keys="selectedKeys"
        :tree-data="regionData"
        block-node
        show-line
        show-icon
        default-expand-all
        :field-names="{ title: 'label', key: 'value', children: 'children' }"
      >
      </a-tree>
      <SlEmpty v-else />
    </div>
    <div class="flex-1 flex flex-col overflow-hidden">
      <div class="mb-4">
        <a-button type="primary" @click="showCreateModal">新增社区</a-button>
      </div>
      <div class="flex-1 overflow-hidden">
        <SlTable
          :columns="columns"
          row-key="id"
          :data-source="tableData"
          :pagination="pagination"
          :loading="tableLoading"
        >
          <template #bodyCell="{ column, record }">
            <div v-if="column.key === 'oper'">
              <a @click="showUpdateModal(record)">编辑</a>
              <a class="ml-2 text-red-400" @click="handleDelete(record)">删除</a>
            </div>
          </template>
        </SlTable>
      </div>
    </div>
    <CURDDialog
      id-key="id"
      create-title="新增社区"
      update-title="编辑社区"
      delete-message="确认删除该社区吗？"
      :show-options="showOptions"
      :model="model"
      :model-form-setting="modelFormSetting"
      :table-data="tableData"
      :curd="curd"
      :reload-table="reloadTable"
    />
  </CommonPage>
</template>
<script setup lang="ts">
import { computed, h, onMounted, ref, watch } from "vue";
import { useCURD } from "/@/hooks/useCURD";
import { TableProps } from "ant-design-vue";
import { findItemByKey, findParents, loopItem } from "/@/utils/treeData";
import { DeptType, DictItem, DictTypeCode, MenuItem, RoleItem } from "/@/api/main/system/models";
import { getRoleMenuIds, getMenuList, getDictOptions, getDeptList } from "/@/api/main/system";
import { Api } from "/@/api/main/community";
import {
  CURDAction,
  CURDModalEvent,
  FormItemComponentType,
  FormItemData,
  ShowCURDModalOptions,
} from "/@/components/CURDDialog/models";
import { PatternKey } from "/@/utils/verify";
import MenuTree from "/@/components/MenuTree.vue";
import { cloneDeep } from "lodash-es";
import { CommunityItem } from "/@/api/main/community/models";
import { SelectOptionItem } from "/@/types/antd";
import { DeptPropertyRoot } from "/@/base/data";
/**
 * 行政区域树
 */
const regionData = ref<SelectOptionItem[]>([]);
const loadingRegion = ref(false);
const selectedKeys = ref<number[]>([]);
onMounted(async () => {
  loadingRegion.value = true;
  const data = await getDictOptions({ typeCode: DictTypeCode.region });
  loadingRegion.value = false;
  if (data) {
    regionData.value = data;
    if (data.length > 0) {
      selectedKeys.value = [data[0].value as number];
    }
  }
});
watch(selectedKeys, (keys) => {
  if (keys.length > 0) {
    reloadTable({
      model: {
        adminRegionId: keys[0],
      },
    });
  }
});
/**
 * 社区表格
 */
const columns = ref<TableProps<CommunityItem>["columns"]>([
  {
    title: "社区编号",
    dataIndex: "code",
  },
  {
    title: "社区名称",
    dataIndex: "name",
  },
  {
    title: "合作框架",
    dataIndex: "cooperationName",
  },
  {
    title: "行政区域",
    dataIndex: "adminRegionName",
  },
  {
    title: "物业公司",
    dataIndex: "propCompanyName",
  },
  {
    title: "操作",
    key: "oper",
    width: 100,
  },
]);
const { pagination, tableData, tableLoading, curd, reloadTable } = useCURD<CommunityItem>({
  getPageUrl: Api.communityDefPage,
  cudUrl: Api.communityDef,
  loadOnMounted: false,
});
/**
 * 增加修改弹窗
 */
const showOptions = ref<ShowCURDModalOptions>();
const model = ref<Partial<CommunityItem>>({
  name: "",
  code: "",
  cooperationId: null,
  adminRegionId: null,
  propCompanyId: null,
  sort: 1,
});
const modelFormSetting: FormItemData<Partial<CommunityItem>>[] = [
  {
    key: "name",
    max: 32,
    pattern: PatternKey.name,
    required: true,
    label: "社区名称",
  },
  {
    key: "code",
    max: 32,
    pattern: PatternKey.code,
    required: true,
    label: "社区编码",
  },
  {
    key: "cooperationId",
    type: FormItemComponentType.TREESELECT,
    label: "合作框架",
    props: {
      treeData: [],
      fieldNames: { label: "name", value: "id" },
    },
    async getData() {
      const data = await getDeptList({ type: DeptType.cooperation });
      return data || [];
    },
  },
  {
    key: "adminRegionId",
    type: FormItemComponentType.TREESELECT,
    label: "行政区域",
    props: {
      treeData: [],
    },
    async getData() {
      const data = await getDictOptions({ typeCode: DictTypeCode.region });
      return data || [];
    },
  },
  {
    key: "propCompanyId",
    type: FormItemComponentType.SELECT,
    label: "物业公司",
    props: {
      options: [],
      // fieldNames: { label: "name", value: "id" },
    },
    async getData() {
      const data = await getDeptList({ type: DeptType.cooperation });
      //找到物业合作下一层的节点数据
      if (data) {
        const re = findItemByKey(data, DeptPropertyRoot, {
          keyName: "name",
        });
        if (re) {
          const chs = re.item.children;
          if (chs && chs.length > 0) {
            return chs.map((el) => ({
              value: el.id,
              label: el.name,
            }));
          }
        }
      }
      return [];
    },
  },
  {
    key: "sort",
    label: "排序",
    type: FormItemComponentType.NUMBER,
  },
];
function showCreateModal() {
  showOptions.value = { action: CURDAction.CREATE };
}
function showUpdateModal(record) {
  showOptions.value = { action: CURDAction.UPDATE, record };
}
function handleDelete(record) {
  showOptions.value = { action: CURDAction.DELETE, ids: [record.id] };
}
</script>
